package com.glodon.paas.account.service.impl;

import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.glodon.paas.account.api.bean.AccountConstant;
import com.glodon.paas.account.biz.UserBiz;
import com.glodon.paas.account.dao.domain.UserEntity;
import com.glodon.paas.account.service.PasswordService;
import com.glodon.paas.exception.PaasServerExceptionFactory;
import com.glodon.paas.exception.i18n.ErrorCode;
import com.glodon.paas.mail.SpringMailMessage;
import com.glodon.paas.mail.SpringMailSender;
import com.glodon.paas.util.GenericsUtil;

@Service("passwordService")
public class PasswordServiceImpl implements PasswordService{
	
	@Autowired
	private UserBiz userBiz;
	
	@Autowired
	private SpringMailSender mailSender;
	
	@Override
	public void resetPassword(String userId, String newPassword, String authorization, Integer authorizationType){
		userBiz.resetPassword(userId, newPassword,authorization,authorizationType);
	}
	
	@Override
	public void emailResetPasswordLink(String email,String path){		
		UserEntity dbuser = userBiz.getUserByAccountName(email, AccountConstant.ACCOUNT_NAME_EMAIL, AccountConstant.USER_STATUS_ACTIVE);
		if (dbuser == null) {
			throw PaasServerExceptionFactory.notFoundException("can not find user["+email+"]", null).setErrorCode(ErrorCode.USER_NOT_EXIST);
		}
		long time=System.currentTimeMillis();
		String token=genToken(dbuser,time);
		String link=path+"/validateResetPasswordLink?email="+email+"&time="+time+"&token="+token;
		HashMap<String,Object> data=new HashMap<String,Object>();
		data.put("link", link);
		//mail.sendAsync(data,new String[]{email});

		SpringMailMessage mailContent = new SpringMailMessage();
		mailContent.setTo(new String[]{email});
		mailContent.setTemplateParam(data);
		//TODO 参数需要配置化
		mailContent.setSubject("重置密码");
		mailContent.setTemplateLocation("mailTemplate/account_emailResetPassword.vm");
		mailSender.sendAsync(mailContent);
	}

	@Override
	public void validateResetPasswordLink(String email, long time, String token1){
		UserEntity dbuser = userBiz.getUserByAccountName(email, AccountConstant.ACCOUNT_NAME_EMAIL, AccountConstant.USER_STATUS_ACTIVE);
		if (dbuser == null) {
			throw PaasServerExceptionFactory.notFoundException("can not find user["+email+"]", null).setErrorCode(ErrorCode.USER_NOT_EXIST);
		}
		if (System.currentTimeMillis() - time > 1 * 24 * 60 * 60 * 1000) {
			throw PaasServerExceptionFactory.accessForbidden("password url has losed effectiveness!", null);
		}
		String realToken=genToken(dbuser,time);
		if(!realToken.equals(token1)){
			throw PaasServerExceptionFactory.validateException("link error!", null).setErrorCode(ErrorCode.LINKED_ERROR);
		}
	}

	private String genToken(UserEntity user, long time) {
		String text = "[md5]" + "|" + user.getId() + "|" + user.getEmail()
				+ "|" + user.getPassword() + "|" + time + "|[md5]";
		return GenericsUtil.md5(text);
	}
}
